package com.zzxz.practicaltrainingsys.service.impl;

import com.zzxz.practicaltrainingsys.entity.Image;
import com.zzxz.practicaltrainingsys.mapper.ImageMapper;
import com.zzxz.practicaltrainingsys.service.ImageService;
import com.zzxz.practicaltrainingsys.util.AvatarUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageMapper imageMapper;

    @Override
    public boolean updateImagePath(Image image) {
        return imageMapper.updateImagePath(image) > 0;
    }

    @Override
    public String getImagePath(Image image) {
        return imageMapper.getImagePath(image);
    }

    @Override
    public String uploadAvatar(String role, Integer userId, MultipartFile file) {
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID() + fileExtension;

            // 获取存储路径
            String uploadPath = AvatarUtil.getAvatarUploadPath(role);
            File dest = new File(uploadPath + File.separator + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);

            // 获取访问路径
            String accessPath = AvatarUtil.getAvatarAccessPath(role, fileName);

            // 更新数据库
            Image image = new Image();
            image.setRole(role);
            image.setUserId(userId);
            image.setImagePath(accessPath);
            updateImagePath(image);

            return accessPath;
        } catch (Exception e) {
            throw new RuntimeException("头像上传失败: " + e.getMessage(), e);
        }
    }
}